// 选项页面主要功能模块
class OptionsManager {
  constructor() {
    this.currentSection = 'general';
    this.currentMockId = null;
    this.currentRequestDetails = null;
    this.init();
  }

  // 初始化
  async init() {
    this.bindEvents();
    await this.loadData();
    await this.loadRequestHistory();

    // 初始化存储记录面板
    await this.loadStorageData();

    this.updateUI();
  }

  // 绑定事件
  bindEvents() {
    // 导航菜单
    document.querySelectorAll('.nav-item').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const section = item.dataset.section;
        this.switchSection(section);

        // 如果切换到存储记录面板，刷新数据
        if (section === 'storage') {
          this.loadStorageData();
        }
      });
    });

    // 基本设置
    this.bindGeneralSettings();

    // 域名白名单
    this.bindWhitelistEvents();

    // Mock规则
    this.bindMockEvents();

    // 请求历史
    this.bindRequestEvents();

    // 导入导出
    this.bindImportExportEvents();

    // 存储记录
    this.bindStorageEvents();
  }

  // 切换页面区块
  switchSection(section) {
    // 更新导航状态
    document.querySelectorAll('.nav-item').forEach(item => {
      item.classList.remove('active');
    });
    document.querySelector(`[data-section="${section}"]`).classList.add('active');

    // 更新内容区域
    document.querySelectorAll('.content-section').forEach(section => {
      section.classList.remove('active');
    });
    document.getElementById(`${section}-section`).classList.add('active');

    this.currentSection = section;

    // 加载对应数据
    this.loadSectionData(section);
  }

  // 加载区块数据
  async loadSectionData(section) {
    switch (section) {
      case 'whitelist':
        await this.loadWhitelist();
        break;
      case 'mocks':
        await this.loadMocks();
        break;
      case 'requests':
        await this.loadRequests();
        break;
    }
  }

  // 绑定基本设置事件
  bindGeneralSettings() {
    // 插件启用/禁用
    const pluginEnabled = document.getElementById('plugin-enabled');
    pluginEnabled.addEventListener('change', async (e) => {
      await this.saveSetting('enabled', e.target.checked);
      this.showAlert('设置已保存', 'success');
    });

    // 自动清理
    const autoCleanup = document.getElementById('auto-cleanup');
    autoCleanup.addEventListener('change', async (e) => {
      await this.saveSetting('autoCleanup', e.target.checked);
    });

    // 清理天数
    const cleanupDays = document.getElementById('cleanup-days');
    cleanupDays.addEventListener('change', async (e) => {
      await this.saveSetting('cleanupDays', parseInt(e.target.value));
    });

    // 最大请求数
    const maxRequests = document.getElementById('max-requests');
    maxRequests.addEventListener('change', async (e) => {
      await this.saveSetting('maxRequests', parseInt(e.target.value));
    });

    // 显示通知
    const showNotifications = document.getElementById('show-notifications');
    showNotifications.addEventListener('change', async (e) => {
      await this.saveSetting('showNotifications', e.target.checked);
    });
  }

  // 绑定域名白名单事件
  bindWhitelistEvents() {
    // 添加域名
    const addBtn = document.getElementById('add-domain-btn');
    const domainInput = document.getElementById('domain-input');

    addBtn.addEventListener('click', () => this.addDomain());
    domainInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') this.addDomain();
    });

    // 示例标签点击
    document.querySelectorAll('.example-tag').forEach(tag => {
      tag.addEventListener('click', () => {
        domainInput.value = tag.textContent;
      });
    });

    // 清空全部
    document.getElementById('clear-domains-btn').addEventListener('click', () => {
      this.clearAllDomains();
    });

    // 批量导入
    document.getElementById('import-domains-btn').addEventListener('click', () => {
      this.importDomains();
    });
  }

  // 绑定Mock事件
  bindMockEvents() {
    // 新增Mock
    document.getElementById('add-mock-btn').addEventListener('click', () => {
      this.openMockModal();
    });

    // 导入Mock
    document.getElementById('import-mock-btn').addEventListener('click', () => {
      this.importMocks();
    });

    // 导出Mock
    document.getElementById('export-mock-btn').addEventListener('click', () => {
      this.exportMocks();
    });

    // Mock过滤
    const mockFilter = document.getElementById('mock-filter');
    const statusFilter = document.getElementById('mock-status-filter');

    mockFilter.addEventListener('input', () => this.filterMocks());
    statusFilter.addEventListener('change', () => this.filterMocks());

    // Mock弹窗事件
    this.bindMockModalEvents();
  }

  // 绑定Mock弹窗事件
  bindMockModalEvents() {
    // 关闭弹窗
    document.getElementById('close-modal').addEventListener('click', () => {
      this.closeMockModal();
    });

    // 取消按钮
    document.getElementById('cancel-mock-btn').addEventListener('click', () => {
      this.closeMockModal();
    });

    // 保存按钮
    document.getElementById('save-mock-btn').addEventListener('click', () => {
      this.saveMock();
    });

    // JSON工具
    document.getElementById('format-json-btn').addEventListener('click', () => {
      this.formatJSON();
    });

    document.getElementById('validate-json-btn').addEventListener('click', () => {
      this.validateJSON();
    });

    // 点击遮罩关闭
    document.getElementById('mock-modal').addEventListener('click', (e) => {
      if (e.target.id === 'mock-modal') {
        this.closeMockModal();
      }
    });
  }

  // 绑定请求历史事件
  bindRequestEvents() {
    // 清空历史
    document.getElementById('clear-requests-btn').addEventListener('click', () => {
      this.clearRequests();
    });

    // 导出数据
    document.getElementById('export-requests-btn').addEventListener('click', () => {
      this.exportRequests();
    });

    // 刷新
    document.getElementById('refresh-requests-btn').addEventListener('click', () => {
      this.loadRequests();
    });

    // 过滤器
    const filters = ['request-url-filter', 'request-method-filter', 'request-status-filter', 'request-date-filter'];
    filters.forEach(id => {
      document.getElementById(id).addEventListener('input', () => this.filterRequests());
    });
  }

  // 绑定导入导出事件
  bindImportExportEvents() {
    // 导出数据
    const exportBtn = document.getElementById('export-data-btn');
    if (exportBtn) {
      exportBtn.addEventListener('click', () => {
        this.exportAllData();
      });
    }

    // 导入数据
    const importBtn = document.getElementById('import-data-btn');
    if (importBtn) {
      importBtn.addEventListener('click', () => {
        const importFile = document.getElementById('import-file');
        if (importFile) importFile.click();
      });
    }

    // 文件选择
    const importFile = document.getElementById('import-file');
    if (importFile) {
      importFile.addEventListener('change', (e) => {
        this.handleFileImport(e.target.files[0]);
      });
    }

    // 请求详情弹窗事件
    const closeRequestDetail = document.getElementById('close-request-detail');
    const closeDetailModal = document.getElementById('close-detail-modal');

    if (closeRequestDetail) {
      closeRequestDetail.addEventListener('click', () => {
        this.hideRequestDetails();
      });
    }
    if (closeDetailModal) {
      closeDetailModal.addEventListener('click', () => {
        this.hideRequestDetails();
      });
    }

    // 拖拽上传
    const dropZone = document.getElementById('file-drop-zone');
    if (dropZone) {
      dropZone.addEventListener('click', () => {
        const importFile = document.getElementById('import-file');
        if (importFile) importFile.click();
      });

      dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
      });

      dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
      });

      dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        const file = e.dataTransfer.files[0];
        if (file) this.handleFileImport(file);
      });
    }
  }

  // 加载数据
  async loadData() {
    try {
      const result = await chrome.storage.local.get([
        'settings', 'whitelist', 'mockList', 'requestHistory'
      ]);

      this.settings = result.settings || {
        enabled: true,
        autoCleanup: true,
        cleanupDays: 30,
        maxRequests: 1000,
        showNotifications: false
      };

      this.whitelist = result.whitelist || [];
      this.mockList = result.mockList || [];
      this.requestHistory = result.requestHistory || [];

      this.updateGeneralSettings();
    } catch (error) {
      console.error('加载数据失败:', error);
      this.showAlert('加载数据失败', 'error');
    }
  }

  // 更新基本设置UI
  updateGeneralSettings() {
    document.getElementById('plugin-enabled').checked = this.settings.enabled;
    document.getElementById('auto-cleanup').checked = this.settings.autoCleanup;
    document.getElementById('cleanup-days').value = this.settings.cleanupDays;
    document.getElementById('max-requests').value = this.settings.maxRequests;
    document.getElementById('show-notifications').checked = this.settings.showNotifications;
  }

  // 保存设置
  async saveSetting(key, value) {
    this.settings[key] = value;
    await chrome.storage.local.set({ settings: this.settings });

    // 通知后台脚本设置变更
    chrome.runtime.sendMessage({
      type: 'SETTINGS_UPDATED',
      settings: this.settings
    });
  }

  // 添加域名
  async addDomain() {
    const input = document.getElementById('domain-input');
    const domain = input.value.trim();

    if (!domain) {
      this.showAlert('请输入域名', 'warning');
      return;
    }

    if (this.whitelist.includes(domain)) {
      this.showAlert('域名已存在', 'warning');
      return;
    }

    this.whitelist.push(domain);
    await this.saveWhitelist();
    input.value = '';
    this.renderWhitelist();
    this.showAlert('域名添加成功', 'success');
  }

  // 删除域名
  async removeDomain(domain) {
    const index = this.whitelist.indexOf(domain);
    if (index > -1) {
      this.whitelist.splice(index, 1);
      await this.saveWhitelist();
      this.renderWhitelist();
      this.showAlert('域名删除成功', 'success');
    }
  }

  // 清空所有域名
  async clearAllDomains() {
    if (confirm('确定要清空所有域名吗？')) {
      this.whitelist = [];
      await this.saveWhitelist();
      this.renderWhitelist();
      this.showAlert('已清空所有域名', 'success');
    }
  }

  // 保存白名单
  async saveWhitelist() {
    await chrome.storage.local.set({ whitelist: this.whitelist });
    chrome.runtime.sendMessage({
      type: 'WHITELIST_UPDATED',
      whitelist: this.whitelist
    });
  }

  // 加载白名单
  async loadWhitelist() {
    this.renderWhitelist();
  }

  // 渲染白名单
  renderWhitelist() {
    var container = document.getElementById('domain-list-container');
    const countElement = document.getElementById('domain-count');

    countElement.textContent = this.whitelist.length;

    if (this.whitelist.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <span class="empty-icon">🌐</span>
          <h3>暂无域名</h3>
          <p>添加需要拦截的域名前缀</p>
        </div>
      `;
      return;
    }

    container.innerHTML = this.whitelist.map(domain => `
      <div class="domain-item">
        <div class="domain-info">
          <div class="domain-url">${domain}</div>
          <div class="domain-stats">已添加到白名单</div>
        </div>
        <div class="domain-actions">
          <button class="btn btn-small btn-outline" data-action="remove-domain" data-domain="${domain}">删除</button>
        </div>
      </div>
    `).join('');

    // 绑定删除按钮事件
    container.querySelectorAll('[data-action="remove-domain"]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const domain = e.target.dataset.domain;
        this.removeDomain(domain);
      });
    });
  }

  // 打开Mock弹窗
  openMockModal(mockData = null) {
    const modal = document.getElementById('mock-modal');
    const title = document.getElementById('modal-title');

    if (mockData) {
      title.textContent = '编辑Mock规则';
      this.currentMockId = mockData.id;
      this.fillMockForm(mockData);
    } else {
      title.textContent = '新增Mock规则';
      this.currentMockId = null;
      this.clearMockForm();
    }

    modal.classList.add('show');
  }

  // 关闭Mock弹窗
  closeMockModal() {
    document.getElementById('mock-modal').classList.remove('show');
    this.currentMockId = null;
  }

  // 填充Mock表单
  fillMockForm(mockData) {
    document.getElementById('mock-url').value = mockData.originUrl || '';
    document.getElementById('mock-method').value = mockData.method || '';
    document.getElementById('mock-status').value = mockData.statusCode || 200;
    document.getElementById('mock-delay').value = mockData.delay || 0;
    document.getElementById('mock-description').value = mockData.description || '';
    document.getElementById('mock-headers').value = JSON.stringify(mockData.headers || {}, null, 2);
    document.getElementById('mock-json').value = JSON.stringify(mockData.mockjson || {}, null, 2);
    document.getElementById('mock-enabled').checked = !mockData.disabled;
  }

  // 清空Mock表单
  clearMockForm() {
    document.getElementById('mock-url').value = '';
    document.getElementById('mock-method').value = '';
    document.getElementById('mock-status').value = '200';
    document.getElementById('mock-delay').value = '0';
    document.getElementById('mock-description').value = '';
    document.getElementById('mock-headers').value = '{\n  "Content-Type": "application/json"\n}';
    document.getElementById('mock-json').value = '{\n  "success": true,\n  "data": {}\n}';
    document.getElementById('mock-enabled').checked = true;
  }

  // 保存Mock
  async saveMock() {
    try {
      const mockData = {
        id: this.currentMockId || Date.now().toString(),
        originUrl: document.getElementById('mock-url').value.trim(),
        method: document.getElementById('mock-method').value,
        statusCode: parseInt(document.getElementById('mock-status').value),
        delay: parseInt(document.getElementById('mock-delay').value),
        description: document.getElementById('mock-description').value.trim(),
        headers: JSON.parse(document.getElementById('mock-headers').value || '{}'),
        mockjson: JSON.parse(document.getElementById('mock-json').value || '{}'),
        disabled: !document.getElementById('mock-enabled').checked,
        createdAt: this.currentMockId ? undefined : new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };

      if (!mockData.originUrl) {
        this.showAlert('请输入URL匹配规则', 'warning');
        return;
      }

      if (this.currentMockId) {
        // 编辑
        const index = this.mockList.findIndex(m => m.id === this.currentMockId);
        if (index > -1) {
          this.mockList[index] = { ...this.mockList[index], ...mockData };
        }
      } else {
        // 新增
        this.mockList.push(mockData);
      }

      await this.saveMockList();
      this.closeMockModal();
      this.renderMocks();
      this.showAlert('Mock规则保存成功', 'success');
    } catch (error) {
      console.error('保存Mock失败:', error);
      this.showAlert('保存失败，请检查JSON格式', 'error');
    }
  }

  // 删除Mock
  async deleteMock(id) {
    if (confirm('确定要删除这个Mock规则吗？')) {
      const index = this.mockList.findIndex(m => m.id === id);
      if (index > -1) {
        this.mockList.splice(index, 1);
        await this.saveMockList();
        this.renderMocks();
        this.showAlert('Mock规则删除成功', 'success');
      }
    }
  }

  // 切换Mock状态
  async toggleMock(id) {
    const mock = this.mockList.find(m => m.id === id);
    if (mock) {
      mock.disabled = !mock.disabled;
      mock.updatedAt = new Date().toISOString();
      await this.saveMockList();
      this.renderMocks();
      this.showAlert(`Mock规则已${mock.disabled ? '禁用' : '启用'}`, 'success');
    }
  }

  // 保存Mock列表
  async saveMockList() {
    await chrome.storage.local.set({ mockList: this.mockList });
    chrome.runtime.sendMessage({
      type: 'MOCK_LIST_UPDATED',
      mockList: this.mockList
    });
  }

  // 加载Mock列表
  async loadMocks() {
    this.renderMocks();
  }

  // 渲染Mock列表
  renderMocks() {
    var container = document.getElementById('mock-list-container');
    const countElement = document.getElementById('mock-count');

    const filteredMocks = this.getFilteredMocks();
    countElement.textContent = filteredMocks.length;

    if (filteredMocks.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <span class="empty-icon">🎭</span>
          <h3>暂无Mock规则</h3>
          <p>创建Mock规则来拦截和模拟API响应</p>
        </div>
      `;
      return;
    }

    container.innerHTML = filteredMocks.map(mock => `
      <div class="mock-item">
        <div class="mock-header">
          <div class="mock-info">
            <div class="mock-url">${mock.originUrl}</div>
            <div class="mock-meta">
              <span>方法: ${mock.method || '所有'}</span>
              <span>状态码: ${mock.statusCode}</span>
              <span>延迟: ${mock.delay}ms</span>
              ${mock.description ? `<span>描述: ${mock.description}</span>` : ''}
            </div>
          </div>
          <div class="mock-status">
            <span class="status-indicator ${mock.disabled ? 'disabled' : ''}"></span>
            <span>${mock.disabled ? '已禁用' : '已启用'}</span>
          </div>
          <div class="mock-actions-list">
            <button class="btn btn-small btn-outline" data-action="toggle-mock" data-mock-id="${mock.id}">
              ${mock.disabled ? '启用' : '禁用'}
            </button>
            <button class="btn btn-small btn-outline" data-action="edit-mock" data-mock-id="${mock.id}">
              编辑
            </button>
            <button class="btn btn-small btn-outline" data-action="delete-mock" data-mock-id="${mock.id}">
              删除
            </button>
          </div>
        </div>
        <div class="mock-body">
          <div class="mock-json-preview">${JSON.stringify(mock.mockjson, null, 2)}</div>
        </div>
      </div>
    `).join('');

    // 绑定Mock操作按钮事件
    var container = document.getElementById('mock-list');
    container.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const action = e.target.dataset.action;
        const mockId = e.target.dataset.mockId;

        switch (action) {
          case 'toggle-mock':
            this.toggleMock(mockId);
            break;
          case 'edit-mock':
            const mock = this.mockList.find(m => m.id === mockId);
            if (mock) this.openMockModal(mock);
            break;
          case 'delete-mock':
            this.deleteMock(mockId);
            break;
        }
      });
    });
  }

  // 获取过滤后的Mock列表
  getFilteredMocks() {
    const filter = document.getElementById('mock-filter')?.value.toLowerCase() || '';
    const statusFilter = document.getElementById('mock-status-filter')?.value || '';

    return this.mockList.filter(mock => {
      const matchesFilter = !filter ||
        mock.originUrl.toLowerCase().includes(filter) ||
        (mock.description && mock.description.toLowerCase().includes(filter));

      const matchesStatus = !statusFilter ||
        (statusFilter === 'enabled' && !mock.disabled) ||
        (statusFilter === 'disabled' && mock.disabled);

      return matchesFilter && matchesStatus;
    });
  }

  // 过滤Mock
  filterMocks() {
    this.renderMocks();
  }

  // 格式化JSON
  formatJSON() {
    try {
      const textarea = document.getElementById('mock-json');
      const json = JSON.parse(textarea.value);
      textarea.value = JSON.stringify(json, null, 2);
      this.showAlert('JSON格式化成功', 'success');
    } catch (error) {
      this.showAlert('JSON格式错误', 'error');
    }
  }

  // 验证JSON
  validateJSON() {
    try {
      const jsonValue = document.getElementById('mock-json').value;
      const headersValue = document.getElementById('mock-headers').value;

      JSON.parse(jsonValue);
      JSON.parse(headersValue);

      this.showAlert('JSON格式正确', 'success');
    } catch (error) {
      this.showAlert('JSON格式错误: ' + error.message, 'error');
    }
  }

  // 加载请求历史
  async loadRequests() {
    this.renderRequests();
    this.updateRequestStats();
  }

  // 加载请求历史数据
  async loadRequestHistory() {
    try {
      // const result = await chrome.storage.local.get(['requestHistory']);
      const result = await chrome.storage.local.get(['requestList']);
      console.log("🚀 ~ OptionsManager ~ loadRequestHistory ~ result:", result)
      this.requestHistory = result?.requestList||[]
      this.renderRequests();
      this.updateRequestStats();
    } catch (error) {
      console.error('加载请求历史失败:', error);
    }
  }

  // 渲染请求列表
  renderRequests() {
    const tableElement = document.getElementById('request-table');
    const countElement = document.getElementById('request-count');
    const filteredRequests = this.getFilteredRequests();
    console.log("🚀 ~ OptionsManager ~ renderRequests ~ filteredRequests:", filteredRequests)


    if (countElement) {
      countElement.textContent = filteredRequests.length;
    }

    if (filteredRequests.length === 0) {
      tableElement.innerHTML = '<div class="empty-state">暂无请求记录</div>';
      return;
    }

    const tableHTML = `
      <table class="table">
        <thead>
          <tr>
            <th>方法</th>
            <th>URL</th>
            <th>状态码</th>
            <th>时间</th>
            <th>Mock</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          ${filteredRequests.map(request => `
            <tr>
              <td><span class="method-badge method-${request.method.toLowerCase()}">${request.method}</span></td>
              <td class="url-cell" title="${request.url}">${request.url}</td>
              <td><span class="status-badge status-${Math.floor((request.statusCode || request.responseCode || 200) / 100)}xx">${request.statusCode || request.responseCode || 200}</span></td>
              <td>${new Date(request.timestamp).toLocaleTimeString()}</td>
              <td>${request.isMocked ? '✓' : '-'}</td>
              <td>
                <button class="btn btn-small btn-outline" data-action="view-request" data-request-id="${request.id}">查看</button>
                <button class="btn btn-small btn-outline" data-action="create-mock-from-request" data-request-id="${request.id}">Mock</button>
              </td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;

    tableElement.innerHTML = tableHTML;

    // 绑定请求操作按钮事件
    tableElement.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const action = e.target.dataset.action;
        const requestId = e.target.dataset.requestId;

        switch (action) {
          case 'view-request':
            this.viewRequestDetails(requestId);
            break;
          case 'create-mock-from-request':
            this.createMockFromRequestId(requestId);
            break;
        }
      });
    });
  }

  // 查看请求详情
  viewRequestDetails(requestId) {
    const request = this.requestHistory.find(r => r.id === requestId);
    if (!request) return;

    // 显示弹窗
    const modal = document.getElementById('request-detail-modal');
    const content = document.getElementById('request-detail-content');

    content.innerHTML = `
      <div class="detail-section">
        <h4>基本信息</h4>
        <p><strong>方法:</strong> ${request.method}</p>
        <p><strong>URL:</strong> ${request.url}</p>
        <p><strong>状态码:</strong> ${request.statusCode || request.responseCode || 200}</p>
        <p><strong>时间:</strong> ${new Date(request.timestamp).toLocaleString()}</p>
      </div>
      <div class="detail-section">
        <h4>请求头</h4>
        <pre>${JSON.stringify(request.requestHeaders || {}, null, 2)}</pre>
      </div>
      <div class="detail-section">
        <h4>查询参数</h4>
        <pre>${JSON.stringify(request.params || request.queryParams || {}, null, 2)}</pre>
      </div>
      <div class="detail-section">
        <h4>请求体</h4>
        <pre>${request.requestBody || '无请求体'}</pre>
      </div>
      <div class="detail-section">
        <h4>响应</h4>
        <pre>${request.responseBody || '无响应数据'}</pre>
      </div>
    `;

    modal.style.display = 'block';

    // 设置创建Mock按钮的请求ID
    const createMockBtn = document.getElementById('create-mock-from-detail');
    if (createMockBtn) {
      createMockBtn.addEventListener('click', () => this.createMockFromRequestId(requestId));
    }
  }

  // 隐藏请求详情弹窗
  hideRequestDetails() {
    const modal = document.getElementById('request-detail-modal');
    modal.style.display = 'none';
  }

  // 从请求创建Mock规则
  createMockFromRequestId(requestId) {
    const request = this.requestHistory.find(r => r.id === requestId);
    if (!request) return;

    // 隐藏详情弹窗
    this.hideRequestDetails();

    // 切换到Mock管理标签页
    this.showTab('mock-management');

    // 填充Mock表单并打开弹窗
    this.showMockModal();
    document.getElementById('mock-url').value = request.url;
    document.getElementById('mock-method').value = request.method;
    document.getElementById('mock-json').value = request.responseBody || '{"message": "Mock response"}';
    document.getElementById('mock-status').value = request.statusCode || request.responseCode || 200;
  }

  // 获取过滤后的请求列表
  getFilteredRequests() {
    const urlFilter = document.getElementById('request-url-filter')?.value.toLowerCase() || '';
    const methodFilter = document.getElementById('request-method-filter')?.value || '';
    const statusFilter = document.getElementById('request-status-filter')?.value || '';
    const dateFilter = document.getElementById('request-date-filter')?.value || '';

    return this.requestHistory.filter(request => {
      const matchesUrl = !urlFilter || request.url.toLowerCase().includes(urlFilter);
      const matchesMethod = !methodFilter || request.method === methodFilter;

      let matchesStatus = true;
      if (statusFilter) {
        const statusCode = request.statusCode;
        const statusRange = statusFilter.replace('xx', '');
        matchesStatus = Math.floor(statusCode / 100) === parseInt(statusRange);
      }

      let matchesDate = true;
      if (dateFilter) {
        const requestDate = new Date(request.timestamp).toISOString().split('T')[0];
        matchesDate = requestDate === dateFilter;
      }

      return matchesUrl && matchesMethod && matchesStatus && matchesDate;
    }).sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
  }

  // 过滤请求
  filterRequests() {
    this.renderRequests();
    this.updateRequestStats();
  }

  // 更新请求统计
  updateRequestStats() {
    const filteredRequests = this.getFilteredRequests();

    document.getElementById('total-requests').textContent = filteredRequests.length;
    document.getElementById('mock-requests').textContent = filteredRequests.filter(r => r.isMocked).length;
    document.getElementById('success-requests').textContent = filteredRequests.filter(r => r.statusCode >= 200 && r.statusCode < 300).length;
    document.getElementById('error-requests').textContent = filteredRequests.filter(r => r.statusCode >= 400).length;
  }

  // 清空请求历史
  async clearRequests() {
    if (confirm('确定要清空所有请求历史吗？')) {
      this.requestHistory = [];
      await chrome.storage.local.set({ requestList: this.requestHistory });
      this.renderRequests();
      this.updateRequestStats();
      this.showAlert('请求历史已清空', 'success');
    }
  }

  // 导出所有数据
  async exportAllData() {
    const exportOptions = {
      whitelist: document.getElementById('export-whitelist').checked,
      mocks: document.getElementById('export-mocks').checked,
      requests: document.getElementById('export-requests').checked,
      settings: document.getElementById('export-settings').checked
    };

    const exportData = {};

    if (exportOptions.whitelist) exportData.whitelist = this.whitelist;
    if (exportOptions.mocks) exportData.mockList = this.mockList;
    if (exportOptions.requests) exportData.requestHistory = this.requestHistory;
    if (exportOptions.settings) exportData.settings = this.settings;

    exportData.exportTime = new Date().toISOString();
    exportData.version = '1.0.0';

    this.downloadJSON(exportData, `interceptor-backup-${new Date().toISOString().split('T')[0]}.json`);
    this.showAlert('数据导出成功', 'success');
  }

  // 处理文件导入
  async handleFileImport(file) {
    if (!file || !file.name.endsWith('.json')) {
      this.showAlert('请选择JSON格式文件', 'warning');
      return;
    }

    try {
      const text = await file.text();
      const data = JSON.parse(text);

      if (confirm('导入数据将覆盖现有配置，确定继续吗？')) {
        if (data.whitelist) {
          this.whitelist = data.whitelist;
          await this.saveWhitelist();
        }

        if (data.mockList) {
          this.mockList = data.mockList;
          await this.saveMockList();
        }

        if (data.requestHistory) {
          this.requestHistory = data.requestHistory;
          await chrome.storage.local.set({ requestList: this.requestHistory });
        }

        if (data.settings) {
          this.settings = { ...this.settings, ...data.settings };
          await chrome.storage.local.set({ settings: this.settings });
          this.updateGeneralSettings();
        }

        this.updateUI();
        this.showAlert('数据导入成功', 'success');
      }
    } catch (error) {
      console.error('导入失败:', error);
      this.showAlert('导入失败，请检查文件格式', 'error');
    }
  }

  // 下载JSON文件
  downloadJSON(data, filename) {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  // 更新UI
  updateUI() {
    if (this.currentSection === 'whitelist') {
      this.renderWhitelist();
    } else if (this.currentSection === 'mocks') {
      this.renderMocks();
    } else if (this.currentSection === 'requests') {
      this.renderRequests();
      this.updateRequestStats();
    }
  }

  // 绑定存储记录事件
  bindStorageEvents() {
    // 刷新存储数据
    document.getElementById('refresh-storage-btn').addEventListener('click', () => {
      this.loadStorageData();
    });

    // 清空所有存储
    document.getElementById('clear-all-storage-btn').addEventListener('click', () => {
      this.clearAllStorage();
    });

    // 事件委托处理存储项的点击事件
    document.getElementById('storage-items-container').addEventListener('click', (e) => {
      const action = e.target.getAttribute('data-action');
      const key = e.target.getAttribute('data-key');

      if (!action || !key) return;

      switch (action) {
        case 'toggle':
          this.toggleStorageItem(key);
          break;
        case 'copy':
          this.copyStorageData(key);
          break;
        case 'download':
          this.downloadStorageData(key);
          break;
        case 'delete':
          this.deleteStorageItem(key);
          break;
      }
    });
  }

  // 加载存储数据
  async loadStorageData() {
    try {
      let result = {};

      // 检查是否在Chrome扩展环境中
      if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
        // 获取所有已知的存储key
        const storageKeys = [
          'settings', 'whitelist', 'mockList', 'requestList', // options.js中的key
          'webList', 'requestList', 'isEnabled' // background.js中的key
        ];

        result = await chrome.storage.local.get(storageKeys);
      } else {
        // 模拟数据用于演示
        result = {
          settings: {
            enabled: true,
            autoCleanup: false,
            cleanupDays: 7,
            maxRequests: 1000,
            showNotifications: true
          },
          whitelist: [
            'example.com',
            'api.github.com',
            'localhost:3000'
          ],
          mockList: [
            {
              id: '1',
              name: '示例Mock规则',
              url: 'https://api.example.com/*',
              method: 'GET',
              response: { message: 'Hello World' },
              enabled: true
            }
          ],
          requestHistory: [
            {
              id: '1',
              url: 'https://api.example.com/users',
              method: 'GET',
              timestamp: Date.now(),
              status: 200
            }
          ],
          webList: ['example.com', 'test.com'],
          requestList: [],
          isEnabled: true
        };
      }

      this.renderStorageData(result);

      // 更新存储项数量
      const count = Object.keys(result).filter(key => result[key] !== undefined).length;
      document.getElementById('storage-count').textContent = count;

    } catch (error) {
      console.error('加载存储数据失败:', error);
      this.showAlert('加载存储数据失败', 'error');
    }
  }

  // 渲染存储数据
  renderStorageData(storageData) {
    var container = document.getElementById('storage-items-container');

    if (Object.keys(storageData).length === 0) {
      container.innerHTML = `
        <div class="storage-empty">
          <span class="empty-icon">🗄️</span>
          <h3>暂无存储数据</h3>
          <p>插件还没有保存任何数据到Chrome存储中</p>
        </div>
      `;
      return;
    }

    container.innerHTML = Object.entries(storageData)
      .filter(([key, value]) => value !== undefined)
      .map(([key, value]) => {
        const jsonStr = JSON.stringify(value, null, 2);
        const size = this.formatBytes(new Blob([jsonStr]).size);
        const icon = this.getStorageIcon(key);

        return `
           <div class="storage-item" data-key="${key}">
             <div class="storage-item-header" data-action="toggle" data-key="${key}">
               <div class="storage-key">
                 <span class="storage-key-icon">${icon}</span>
                 ${key}
               </div>
               <div class="storage-meta">
                 <span class="storage-size">${size}</span>
                 <span class="storage-toggle">▶</span>
               </div>
             </div>
             <div class="storage-content" style="overflow:auto;">
               <pre class="storage-json">${this.highlightJSON(jsonStr)}</pre>
               <div class="storage-actions-item">
                 <button class="btn-small-outline" data-action="copy" data-key="${key}">
                   📋 复制
                 </button>
                 <button class="btn-small-outline" data-action="download" data-key="${key}">
                   💾 下载
                 </button>
                 <button class="btn-small-danger" data-action="delete" data-key="${key}">
                   🗑️删除
                 </button>
               </div>
             </div>
           </div>
         `;
      }).join('');
  }

  // 获取存储项图标
  getStorageIcon(key) {
    const iconMap = {
      'settings': '⚙️',
      'whitelist': '🌐',
      'mockList': '🎭',
      'requestHistory': '📊',
      'webList': '🌐',
      'requestList': '📋',
      'isEnabled': '🔘'
    };
    return iconMap[key] || '📦';
  }

  // 格式化字节大小
  formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // JSON语法高亮
  highlightJSON(jsonStr) {
    return jsonStr
      .replace(/"([^"]+)":/g, '<span class="json-key">"$1"</span>:')
      .replace(/: "([^"]*)"/g, ': <span class="json-string">"$1"</span>')
      .replace(/: (\d+)/g, ': <span class="json-number">$1</span>')
      .replace(/: (true|false)/g, ': <span class="json-boolean">$1</span>')
      .replace(/: null/g, ': <span class="json-null">null</span>');
  }

  // 切换存储项展开/折叠
  toggleStorageItem(key) {
    const item = document.querySelector(`[data-key="${key}"]`);
    if (item) {
      item.classList.toggle('expanded');
    }
  }

  // 复制存储数据
  async copyStorageData(key) {
    try {
      let result = {};

      if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
        result = await chrome.storage.local.get([key]);
      } else {
        // 从当前显示的数据中获取
        const storageItem = document.querySelector(`[data-key="${key}"] .storage-json`);
        if (storageItem) {
          const jsonText = storageItem.textContent;
          result[key] = JSON.parse(jsonText);
        }
      }

      const jsonStr = JSON.stringify(result[key], null, 2);
      await navigator.clipboard.writeText(jsonStr);
      this.showAlert(`已复制 ${key} 数据到剪贴板`, 'success');
    } catch (error) {
      console.error('复制失败:', error);
      this.showAlert('复制失败', 'error');
    }
  }

  // 下载存储数据
  async downloadStorageData(key) {
    try {
      let result = {};

      if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
        result = await chrome.storage.local.get([key]);
      } else {
        // 从当前显示的数据中获取
        const storageItem = document.querySelector(`[data-key="${key}"] .storage-json`);
        if (storageItem) {
          const jsonText = storageItem.textContent;
          result[key] = JSON.parse(jsonText);
        }
      }

      const data = {
        key: key,
        value: result[key],
        exportTime: new Date().toISOString()
      };
      this.downloadJSON(data, `storage-${key}-${new Date().toISOString().split('T')[0]}.json`);
      this.showAlert(`${key} 数据下载成功`, 'success');
    } catch (error) {
      console.error('下载失败:', error);
      this.showAlert('下载失败', 'error');
    }
  }

  // 删除存储项
  async deleteStorageItem(key) {
    if (confirm(`确定要删除存储项 "${key}" 吗？\n\n注意：删除后可能影响插件正常功能！`)) {
      try {
        if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
          await chrome.storage.local.remove([key]);
        } else {
          // 在演示模式下，只是从界面移除
          const item = document.querySelector(`[data-key="${key}"]`);
          if (item) {
            item.remove();
          }
        }

        this.loadStorageData(); // 重新加载数据
        this.showAlert(`已删除存储项 ${key}`, 'success');
      } catch (error) {
        console.error('删除失败:', error);
        this.showAlert('删除失败', 'error');
      }
    }
  }

  // 清空所有存储
  async clearAllStorage() {
    if (confirm('确定要清空所有Chrome存储数据吗？\n\n警告：这将删除插件的所有配置和数据，操作不可恢复！')) {
      try {
        if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
          await chrome.storage.local.clear();
          // 重新初始化默认数据
          await this.loadData();
        } else {
          // 在演示模式下，清空容器
          var container = document.getElementById('storage-items-container');
          if (container) {
            container.innerHTML = `
              <div class="storage-empty">
                <span class="empty-icon">🗄️</span>
                <h3>暂无存储数据</h3>
                <p>插件还没有保存任何数据到Chrome存储中</p>
              </div>
            `;
          }
          document.getElementById('storage-count').textContent = '0';
        }

        this.showAlert('所有存储数据已清空', 'success');
      } catch (error) {
        console.error('清空存储失败:', error);
        this.showAlert('清空存储失败', 'error');
      }
    }
  }

  // 显示提示信息
  showAlert(message, type = 'info') {
    // 创建提示元素
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.textContent = message;
    alert.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 10000;
      min-width: 300px;
      padding: 12px 16px;
      border-radius: 6px;
      font-size: 14px;
      box-shadow: 0 4px 15px rgba(0,0,0,0.2);
      animation: slideInRight 0.3s ease;
    `;

    document.body.appendChild(alert);

    // 3秒后自动移除
    setTimeout(() => {
      if (alert.parentNode) {
        alert.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
          if (alert.parentNode) {
            document.body.removeChild(alert);
          }
        }, 300);
      }
    }, 3000);
  }
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
  @keyframes slideInRight {
    from {
      opacity: 0;
      transform: translateX(100%);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }
  
  @keyframes slideOutRight {
    from {
      opacity: 1;
      transform: translateX(0);
    }
    to {
      opacity: 0;
      transform: translateX(100%);
    }
  }
`;
document.head.appendChild(style);

// 初始化选项管理器
let optionsManager;
document.addEventListener('DOMContentLoaded', () => {
  optionsManager = new OptionsManager();
});

// 导出到全局作用域供HTML调用
window.optionsManager = optionsManager;